package com.zlt.bkparking.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zlt.bkparking.dto.AppUserDTO;
import com.zlt.bkparking.entity.*;
import com.zlt.bkparking.mapper.*;
import com.zlt.bkparking.service.UserService;
import com.zlt.bkparking.utils.MD5Util;
import com.zlt.bkparking.utils.StringUtil;
import com.zlt.bkparking.vo.ActiveBackUser;
import com.zlt.bkparking.vo.AppUserVO;
import com.zlt.bkparking.vo.Menu;
import com.zlt.bkparking.vo.PermissionVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private UserVipMapper userVipMapper;
    @Autowired
    private ParkingLotMapper parkingLotMapper;
    @Autowired
    private ParkingOrderMapper parkingOrderMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public PageInfo<AppUserVO> selectUsers(AppUserDTO appUserDTO) {

        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }
        //获取当前管理员管理的停车场
        ParkingLotExample parkingLotExample = new ParkingLotExample();
        parkingLotExample.createCriteria().andBuIdEqualTo(1l);  //activeUser.getBuId()
        List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
        int plId = parkingLots.get(0).getPlId();

        //获取是当前管理员管理的停车场 的停车用户
        List<String> auIds = parkingOrderMapper.selectAuId(1);

        // 条件查询开始
        AppUserExample appUserExample =new AppUserExample();
        AppUserExample.Criteria criteria = appUserExample.createCriteria();
        if (appUserDTO.getAuNickname()!=null && StringUtil.isNotNull(appUserDTO.getAuNickname())){
            criteria.andAuNicknameLike("%"+appUserDTO.getAuNickname()+"%");
        }
        if (appUserDTO.getAuPhoto()!=null && StringUtil.isNotNull(appUserDTO.getAuPhoto())){
            criteria.andAuPhoneLike("%"+appUserDTO.getAuPhoto()+"%");
        }
        criteria.andAuIdIn(auIds);
        //条件查询结束

        //开启分页
        PageHelper.startPage(appUserDTO.getPage(),appUserDTO.getLimit());
        //开始查询
        List<AppUser> appUsers = appUserMapper.selectByExample(appUserExample);
        System.out.println("appUsers:===>"+appUsers);
        PageInfo<AppUserVO> pageInfo=new PageInfo(appUsers);
        List<AppUserVO> appUserVOS=new ArrayList<>();
        pageInfo.setList(appUserVOS);

        appUsers.forEach(a ->{
            AppUserVO appUserVO = new AppUserVO();
            BeanUtils.copyProperties(a,appUserVO);
            UserVipExample userVipExample = new UserVipExample();
            UserVipExample.Criteria criteria1 = userVipExample.createCriteria();
            criteria1.andAuIdEqualTo(a.getAuId());
            criteria1.andVtIdEqualTo(1);
            List<UserVip> userVips = userVipMapper.selectByExample(userVipExample);
            if (userVips!=null && !userVips.isEmpty()){
                appUserVO.setVip((byte)0);
            }

            UserVipExample userVipExample2 = new UserVipExample();
            UserVipExample.Criteria criteria2 = userVipExample2.createCriteria();
            criteria2.andAuIdEqualTo(a.getAuId());
            criteria2.andVtIdEqualTo(2);
            List<UserVip> userVip2 = userVipMapper.selectByExample(userVipExample2);
            if (userVip2!=null && !userVip2.isEmpty()){
                appUserVO.setParkVip((byte)0);
            }

            int count =parkingOrderMapper.selectCount(a.getAuId(),plId); //查询停车次数
            appUserVO.setParkCount(count);
            appUserVOS.add(appUserVO);
        });
        return pageInfo;
    }

    @Override
    public boolean insertUser(AppUserDTO appUserDTO) {
        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }
        //获取当前管理员管理的停车场
        ParkingLotExample parkingLotExample = new ParkingLotExample();
        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());  //activeUser.getBuId()
        List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
        int plId = parkingLots.get(0).getPlId();

        AppUser appUser = new AppUser();
        BeanUtils.copyProperties(appUserDTO,appUser);
        appUser.setAuId(StringUtil.uuid());
        String salt=StringUtil.randomStr(6);
        appUser.setAuSalt(salt);
        appUser.setAuPassword(MD5Util.md5(appUserDTO.getAuPassword(),salt));
        int i = appUserMapper.insertSelective(appUser);

        ParkingOrder parkingOrder = new ParkingOrder();
        parkingOrder.setPlId(plId);
        parkingOrder.setPoNo("123456");
        parkingOrder.setPoStart(new Date());
        parkingOrder.setAuId(appUser.getAuId());
        parkingOrderMapper.insertSelective(parkingOrder);
        return i>0;
    }

    @Override
    public boolean updateUser(AppUserDTO appUserDTO) {
        AppUser appUser = new AppUser();
        BeanUtils.copyProperties(appUserDTO,appUser);
        int i = appUserMapper.updateByPrimaryKeySelective(appUser);
        return  i>0;
    }

    @Override
    public boolean rechargeVIP(AppUserDTO appUserDTO,Integer vId) {
        if (appUserDTO.getMonth()==null){
            throw new RuntimeException("月数不能为空!");
        }else{
            UserVipExample userVipExample = new UserVipExample();
            userVipExample.createCriteria().andAuIdEqualTo(appUserDTO.getAuId());
            UserVip userVip = userVipMapper.selectByExample(userVipExample).get(0);

            if ( "0".equals(StringUtil.getDaySub(userVip.getUvEnd(),new Date()))){
                userVip.setUvEnd(StringUtil.getTime(userVip.getUvEnd(),appUserDTO.getMonth()));
            }else {
                userVip.setUvEnd(StringUtil.getTime(new Date(),appUserDTO.getMonth()));
            }

            if (vId==2){
                ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
                if(activeUser==null){
                    throw new RuntimeException("当前未登录");
                }
                //获取当前管理员管理的停车场
                ParkingLotExample parkingLotExample = new ParkingLotExample();
                parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());  //activeUser.getBuId()
                List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
                int plId = parkingLots.get(0).getPlId();
                userVip.setPlId(plId);
                return  userVipMapper.updateByPrimaryKeySelective(userVip) >0;
            }else {
                return  userVipMapper.updateByPrimaryKeySelective(userVip) >0;
            }
        }
    }

    @Override
    public boolean deleteUser(String auId) {
        AppUser appUser = new AppUser();
        appUser.setAuId(auId);
        appUser.setAuState((byte) 2);

        return appUserMapper.updateByPrimaryKeySelective(appUser)>0;
    }


    @Override
    public PageInfo<AppUserVO> selectVipUser(AppUserDTO appUserDTO) {
        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }
        //获取当前管理员管理的停车场
        ParkingLotExample parkingLotExample = new ParkingLotExample();
        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());  //activeUser.getBuId()
        List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
        int plId = parkingLots.get(0).getPlId();

        //获取是当前管理员管理的停车场 的平台VIP用户
        List<String> auIds = parkingOrderMapper.selectVIP(1,1);

        // 条件查询开始
        AppUserExample appUserExample =new AppUserExample();
        AppUserExample.Criteria criteria = appUserExample.createCriteria();
        if (appUserDTO.getAuNickname()!=null && StringUtil.isNotNull(appUserDTO.getAuNickname())){
            criteria.andAuNicknameLike("%"+appUserDTO.getAuNickname()+"%");
        }
        if (appUserDTO.getAuPhoto()!=null && StringUtil.isNotNull(appUserDTO.getAuPhoto())){
            criteria.andAuPhoneLike("%"+appUserDTO.getAuPhoto()+"%");
        }
        criteria.andAuIdIn(auIds);
        //条件查询结束

        //开启分页
        PageHelper.startPage(appUserDTO.getPage(),appUserDTO.getLimit());

        List<AppUser> appUsers = appUserMapper.selectByExample(appUserExample);
        PageInfo<AppUserVO> pageInfo=new PageInfo(appUsers);
        List<AppUserVO> appUserVOS=new ArrayList<>();
        pageInfo.setList(appUserVOS);
        appUsers.forEach(a ->{
            AppUserVO appUserVO = new AppUserVO();
            BeanUtils.copyProperties(a,appUserVO);
            UserVipExample userVipExample = new UserVipExample();
            userVipExample.createCriteria().andAuIdEqualTo(a.getAuId());
            UserVip userVip = userVipMapper.selectByExample(userVipExample).get(0);
            appUserVO.setBeginTime(userVip.getUvStart());
            appUserVO.setSurplus(StringUtil.getDaySub(new Date(),userVip.getUvEnd()));
            int count =parkingOrderMapper.selectCount(a.getAuId(),plId); //查询停车次数
            appUserVO.setParkCount(count);
            appUserVOS.add(appUserVO);
        });
        return pageInfo;
    }


    @Override
    public PageInfo<AppUserVO> selectParkVipUser(AppUserDTO appUserDTO) {
        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }
        //获取当前管理员管理的停车场
        ParkingLotExample parkingLotExample = new ParkingLotExample();
        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());  //activeUser.getBuId()
        List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
        int plId = parkingLots.get(0).getPlId();

        //获取是当前管理员管理的停车场 的停车用户 的停车场VIP
        List<String> auIds = parkingOrderMapper.selectParkVIP(plId);
        // 条件查询开始
        AppUserExample appUserExample =new AppUserExample();
        AppUserExample.Criteria criteria = appUserExample.createCriteria();
        if (appUserDTO.getAuNickname()!=null && StringUtil.isNotNull(appUserDTO.getAuNickname())){
            criteria.andAuNicknameLike("%"+appUserDTO.getAuNickname()+"%");
        }
        if (appUserDTO.getAuPhoto()!=null && StringUtil.isNotNull(appUserDTO.getAuPhoto())){
            criteria.andAuPhoneLike("%"+appUserDTO.getAuPhoto()+"%");
        }
        criteria.andAuIdIn(auIds);
        //条件查询结束

        //开启分页
        PageHelper.startPage(appUserDTO.getPage(),appUserDTO.getLimit());
        List<AppUser> appUsers = appUserMapper.selectByExample(appUserExample);

        PageInfo<AppUserVO> pageInfo=new PageInfo(appUsers);
        List<AppUserVO> appUserVOS=new ArrayList<>();
        pageInfo.setList(appUserVOS);
        appUsers.forEach(a ->{
            AppUserVO appUserVO = new AppUserVO();
            BeanUtils.copyProperties(a,appUserVO);
            UserVipExample userVipExample = new UserVipExample();
            userVipExample.createCriteria().andAuIdEqualTo(a.getAuId());
            List<UserVip> userVips = userVipMapper.selectByExample(userVipExample);
            appUserVO.setBeginTime(userVips.get(0).getUvStart());
            appUserVO.setSurplus(StringUtil.getDaySub(new Date(),userVips.get(0).getUvEnd()));

            int count =parkingOrderMapper.selectCount(a.getAuId(),plId); //查询停车次数
            appUserVO.setParkCount(count);
            appUserVOS.add(appUserVO);
        });
        return pageInfo;
    }

    @Override
    public List<AppUserVO> getNotVipUser(Integer state) {
        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }

        List<String> auIds = new ArrayList<>(); // 会员列表

        //获取当前管理员管理的停车场
        ParkingLotExample parkingLotExample = new ParkingLotExample();
        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());  //activeUser.getBuId()
        List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
        int plId = parkingLots.get(0).getPlId();
        if (state == 0){ //平台会员
            UserVipExample userVipExample = new UserVipExample();
            userVipExample.createCriteria().andVtIdEqualTo(1);
            List<UserVip> userVips = userVipMapper.selectByExample(userVipExample);
            //查询平台会员列表
            for (UserVip userVip : userVips) {
                auIds.add(userVip.getAuId());
            }
        }else {
            //获取是当前管理员管理的停车场 的停车用户中 的停车场VIP
            auIds.addAll(parkingOrderMapper.selectParkVIP(plId));
        }
        //获取非VIP
        List<AppUser> appUsers= appUserMapper.selectNotVip(auIds,plId);
        List<AppUserVO> appUserVOS=new ArrayList<>();
        appUsers.forEach(a ->{
            AppUserVO appUserVO = new AppUserVO();
            BeanUtils.copyProperties(a,appUserVO);
            appUserVOS.add(appUserVO);
        });
        return appUserVOS;
    }

    @Override
    public boolean insertVip(AppUserDTO appUserDTO,Integer state) {
        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }

        UserVip userVip = new UserVip();
        userVip.setAuId(appUserDTO.getAuId());
        userVip.setUvStart(new Date());
        userVip.setUvEnd(StringUtil.getTime(new Date(),appUserDTO.getMonth()));

        if (state==0){
            userVip.setVtId(1);
        }else {
            //获取当前管理员管理的停车场
            ParkingLotExample parkingLotExample = new ParkingLotExample();
            parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());  //activeUser.getBuId()
            List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
            int plId = parkingLots.get(0).getPlId();
            userVip.setVtId(2);
            userVip.setPlId(plId);
        }
        int i = userVipMapper.insertSelective(userVip);

        return i> 0;
    }

    @Override
    public boolean deleteVip(String auId) {
        UserVipExample userVipExample =new UserVipExample();
        UserVipExample.Criteria criteria = userVipExample.createCriteria();
        criteria.andVtIdEqualTo(1);
        criteria.andAuIdEqualTo(auId);
        return userVipMapper.deleteByExample(userVipExample) >0;
    }

    @Override
    public boolean deleteParkVip(String auId) {
        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }
        //获取当前管理员管理的停车场
        ParkingLotExample parkingLotExample = new ParkingLotExample();
        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());  //activeUser.getBuId()
        List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
        int plId = parkingLots.get(0).getPlId();
        UserVipExample userVipExample = new UserVipExample();
        UserVipExample.Criteria criteria=userVipExample.createCriteria();
        criteria.andAuIdEqualTo(auId);
        criteria.andVtIdEqualTo(2);
        criteria.andPlIdEqualTo(plId);

        return userVipMapper.deleteByExample(userVipExample) >0;
    }
//    @Override
//    public boolean deletePassParkVip(String auId) {
//        UserVipExample userVipExample =new UserVipExample();
//        UserVipExample.Criteria criteria = userVipExample.createCriteria();
//        criteria.andVtIdEqualTo(2);
//        criteria.andAuIdEqualTo(auId);
//        return userVipMapper.deleteByExample(userVipExample) >0;
//
//    }

    @Override
    public boolean updateParkVip(AppUserDTO appUserDTO) {
        AppUser appUser = new AppUser();
        BeanUtils.copyProperties(appUserDTO,appUser);
        int i = appUserMapper.updateByPrimaryKeySelective(appUser);
        if (appUserDTO.getMonth()!=0 && appUserDTO.getMonth()!=null){
            UserVipExample userVipExample = new UserVipExample();
            userVipExample.createCriteria().andAuIdEqualTo(appUserDTO.getAuId());
            UserVip userVip = userVipMapper.selectByExample(userVipExample).get(0);

            if ( "0".equals(StringUtil.getDaySub(userVip.getUvEnd(),new Date()))){
                userVip.setUvEnd(StringUtil.getTime(userVip.getUvStart(),appUserDTO.getMonth()));
                userVipMapper.updateByPrimaryKeySelective(userVip);
            }else {
                userVip.setUvEnd(StringUtil.getTime(new Date(),appUserDTO.getMonth()));
                userVipMapper.updateByPrimaryKeySelective(userVip);
            }
        }
        return i>0;
    }

    @Override
    public boolean batchDeleteParkVip(List<String> auIds,Integer state) {
        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        if(activeUser==null){
            throw new RuntimeException("当前未登录");
        }
        //获取当前管理员管理的停车场
        ParkingLotExample parkingLotExample = new ParkingLotExample();
        parkingLotExample.createCriteria().andBuIdEqualTo(activeUser.getBuId());  //activeUser.getBuId()
        List<ParkingLot> parkingLots = parkingLotMapper.selectByExample(parkingLotExample);
        int plId = parkingLots.get(0).getPlId();

        UserVipExample userVipExample = new UserVipExample();
        UserVipExample.Criteria criteria=userVipExample.createCriteria();
        criteria.andAuIdIn(auIds);
        criteria.andVtIdEqualTo(2);
        criteria.andPlIdEqualTo(plId);
        int i = userVipMapper.deleteByExample(userVipExample);
        if (state==1){
            auIds.forEach(auId ->{
                AppUser appUser = new AppUser();
                appUser.setAuId(auId);
                appUser.setAuState((byte)1);
                appUserMapper.updateByPrimaryKeySelective(appUser);
            });
        }

        return i >0;
    }

    @Override
    public List<Menu> selectMenu() {

        ActiveBackUser activeUser = (ActiveBackUser) SecurityUtils.getSubject().getPrincipal();
        List<PermissionVo> permissionVOS = activeUser.getPermissionVos();

//        List<PermissionVo> permissionVOS=new ArrayList<>();
//        List<Permission> permissions = permissionMapper.selectByExample(new PermissionExample());
//        for (Permission permission : permissions) {
//            PermissionVo permissionVo=new PermissionVo();
//            BeanUtils.copyProperties(permission,permissionVo);
//            permissionVOS.add(permissionVo);
//        }

        List<Menu> menus=new ArrayList<>();
        for (PermissionVo permissionVO : permissionVOS) {
            if(permissionVO.getPLevels()==(byte)1){
                Menu menu=new Menu();
                BeanUtils.copyProperties(permissionVO,menu);
                menu.setChildren(new ArrayList<>());
                menus.add(menu);
            }
        }


        for (PermissionVo permissionVO : permissionVOS) {
            if(permissionVO.getPLevels()==(byte)2){
                for (Menu m : menus) {
                    if(permissionVO.getParentId()==m.getPId()){
                        Menu menu = new Menu();
                        BeanUtils.copyProperties(permissionVO,menu);
                        menu.setChildren(new ArrayList<>());
                        m.getChildren().add(menu);
                    }
                }
            }
        }
        return menus;
    }


}
